package com.terry.activity.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.terry.activity.bean.WeChatJsConfig;
import com.terry.activity.bean.constant.CC;
import com.terry.activity.bean.constant.ErrorCode;
import com.terry.activity.bean.exception.WechatAuthException;
import com.terry.activity.bean.message.ResponseMsg;
import com.terry.activity.controller.base.BaseController;
import com.terry.activity.util.CommonUtil;
import com.terry.activity.util.WeChatUtil;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Create On 18/4/19.
 *
 * @author TerrySolar
 */

@Controller
@RequestMapping(value = "/wechat")
public class WeChatController extends BaseController {

    @Resource
    private WeChatUtil wechatUtil;

    @Resource
    private JedisPool jedisPool;


    /**
     * 微信签名校验
     * @param request HttpServletRequest
     * @param response HttpServletResponse
     */
    @RequestMapping(value = "/api", method = RequestMethod.GET)
    public void wechatCheckSign(HttpServletRequest request, HttpServletResponse response) {
        if (wechatUtil.checkSign(request)) {
            try {
                response.getOutputStream().write(request.getParameter("echostr").getBytes());
            } catch (Exception e) {
                logger.error("微信API验证失败!",e);
            }
        }
    }


    /**
     * 微信授权登陆回调
     *
     * @param code 微信code
     * @param state 微信state
     */
    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public String wechatAuthLogin(String code, String state, HttpServletRequest request) {
        String openIdUrl = wechatUtil.constructAccessTokenUrl(code);
        String redirectUrl;

        // 获取Web授权AccessToken
        Connection connection = Jsoup.connect(openIdUrl);

        try {
            connection.get();
        } catch (IOException e) {
            logger.error("获取openid错误！网络请求失败",e);
        }

        // 读取openid
        JSONObject jsonData = JSON.parseObject(connection.response().body());
        String openid = jsonData.getString("openid");

        // 将openid写入session
        request.getSession().setAttribute("openid", openid);

        if (state != null && !state.equals("") && !state.equals("STATE")) {
            return "redirect:" + state;
        } else {
            return "redirect:" + CC.HOSTNAME;
        }

    }


    /**
     * 微信授权认证检查
     *
     * @param request HttpServletRequest
     * @return ResponseMsg
     */
    @RequestMapping(value = "/auth/check", method = RequestMethod.GET)
    @ResponseBody
    @CrossOrigin
    public ResponseMsg wechatAuthCheck(HttpServletRequest request) throws WechatAuthException {
        assertWechatAuth(request);

        return new ResponseMsg(ErrorCode.OK, "OK");

    }


    @ResponseBody
    @RequestMapping(value = "/js/config", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseMsg wechatJsConfig(HttpServletRequest request) throws WechatAuthException {

//        assertWechatAuth(request);

        String url = request.getHeader("Referer");

        Jedis jedis = jedisPool.getResource();
        String jsTicket = jedis.get(CommonUtil.GenerateRedisKey("wechat:jsapi_ticket"));
        jedis.close();

        return responseData(new WeChatJsConfig(jsTicket, url));
    }

}
